#include "chatclient.h"


ChatClient::ChatClient(QWidget *parent) :
    QWidget(parent)
{

}

ChatClient::~ChatClient()
{
    stopClient();
}
/* 开启客户端 */
void ChatClient::startClient(const QBluetoothServiceInfo &remoteService)
{
    if (socket)
        return;

    // Connect to service
    socket = new QBluetoothSocket(QBluetoothServiceInfo::RfcommProtocol);
    qDebug() << "Create socket";
    socket->connectToService(remoteService);
    qDebug() << "ConnectToService done";

    connect(socket, SIGNAL(readyRead()),
    this, SLOT(readSocket()));
    connect(socket, SIGNAL(connected()),
    this, SLOT(connected()));
    connect(socket, SIGNAL(disconnected()),
            this, SIGNAL(disconnected()));
}

void ChatClient::stopClient()
{
    delete socket;
    socket = 0;
}

void ChatClient::sendMessage(const QString &message)
{
    qDebug()<<"Sending data in client: " + message;

    QByteArray text = message.toUtf8() + '\n';
    socket->write(text);
}

void ChatClient::disconnect()
{
    qDebug()<<"Going to disconnect in client";
    if (socket) {
    qDebug()<<"diconnecting...";
    socket->close();
    }
}

void ChatClient::readSocket()
{
    if (!socket)
    return;

    while (socket->canReadLine()) {
    QByteArray line = socket->readLine();
    emit messageReceived(socket->peerName(),
    QString::fromUtf8(line.constData(),
    line.length()));
    }
}

void ChatClient::connected()
{
    emit connected(socket->peerName());
}
